import React from 'react';
import {Table, Row, Col, Form, Input, Icon, InputNumber, Radio, DatePicker, Select, Upload, Button, Switch, Modal, Popconfirm, Tabs, message, Steps} from 'antd';

import OperatorConstant from "../../utils/OperatorConstant";
import Inoviceheader from '../../components/drawback/Inoviceheader'
import Inoviceproducts from '../../components/drawback/Inoviceproducts';
import AddInvoice from '../../components/drawback/AddInvoice';
import Constants from '../../utils/Constants';

const { TextArea } = Input;
const Step = Steps.Step;
const Dragger = Upload.Dragger;
const R = require('ramda');
import moment from 'moment'
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const dateFormat = 'YYYY-MM-DD';




export default Form.create({wrappedComponentRef: true})(class InoviceDetail extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            open: false,
            disabled: true,
            type: "",
            parOrder: "",
            subloading: false

        }
    }



    handleResetFields = () => {
        if(this.inoviceheader){this.inoviceheader.handleCancel()}
        if(this.inoviceproducts){this.inoviceproducts.handleCancel()}
        if(this.addInvoice){this.addInvoice.handleCancel()}

        this.props.form.resetFields();

    }

    handleCancel = () => {
        this.handleResetFields();
        this.setState({open: false});
    }

    handleOpen = (type) => {
        this.state.type = type;
        this.setState({open: true});
    }

    handleConfirm = (changeStatus) => {//changeStatus = 1表示只保存发票不改变收票状态
        if(this.state.type == OperatorConstant.view){
            return;
        }

        let values = this.props.form.getFieldsValue();


        this.props.form.validateFields((errors, values) => {
            if (errors) return;
            this.setState({ subloading: true});
           
            let dataSource = R.isNil(this.props.invoices) || R.isEmpty(this.props.invoices)  ? {} : this.props.invoices[0];

            if(this.state.type == OperatorConstant.drawer_checkinvoice){

                this.props.dispatch({
                    type: 'recinvoices/checkinvoice',
                    payload: {
                        orderId: dataSource.orderId,
                        memo: values.memo,
                        checkStatus: values.checkStatus,
                        checkinvoicetime : values.checkinvoicetime ? values.checkinvoicetime.format(Constants.DATEFORMAT) : "",
                        onSuccess:()=>{
                            this.props.handleSearch();
                            this.handleCancel();
                            this.setState({ subloading:false});
                        },
                        onFail:()=>{
                            this.setState({subloading:false});
                        }
                    }
                });

            }else if(this.state.type == OperatorConstant.add){

                //判断发票数据是否为空
                if(R.isNil(dataSource.taxInvoices) || R.isEmpty(dataSource.taxInvoices)){
                    message.error("请填写发票数据！");
                    this.setState({ subloading:false});
                    return;
                }

                this.props.dispatch({
                    type: 'recinvoices/receiveinvoice',
                    payload: {
                        orderId: dataSource.orderId,
                        list: dataSource.taxInvoices,
                        changeStatus,
                        onSuccess:()=>{
                            this.props.handleSearch();
                            this.handleCancel();
                            this.setState({ subloading:false});
                        },
                        onFail:()=>{
                            this.setState({subloading:false});
                        }
                    }
                });

            }



        });
    }


    handleCollectForm = () => {
        this.form.payOrder = this.refs.payOrder.getUrl();//this.state.orderso;
        return this.form;
    }

    handleSelect=(value)=>{
        this.props.form.setFields({
            approvalmemo:{errors:null},
        });

        if(value==4 || value==5){
            this.state.require_memo=false;
            this.state.require_other=true;
        }else{
            this.state.require_memo=true;
            this.state.require_other=false;
        }
    };

    render() {
        let otherFieldValues = this.props.form.getFieldsValue();
        let invoices = R.isNil(this.props.invoices)  ? {} : this.props.invoices;
        let inoviceproductsList = R.isNil(this.props.inoviceproductsList)  ? [] : this.props.inoviceproductsList;
        let approvalHistory=R.isNil(invoices)?null:invoices[0];
        approvalHistory=R.isNil(approvalHistory)?null:approvalHistory.approvalHistory;
        let memo=R.isNil(approvalHistory)?null:approvalHistory.approvalmemo;

        let memoTitle="收票详情";
        if(!R.isNil(approvalHistory)){
            if(approvalHistory.approvalresult=="6")
            {
                memoTitle=<span>收票详情&nbsp;<p style={{color:"red"}}>收票审核退回原因：{memo}</p></span>;
            }
        }

        let invoiceMemo="";
        if(this.state.type==OperatorConstant.approval){

            let inv= R.isNil(invoices)?null:invoices[0];
            let taxInv= R.isNil(inv)?null:inv.taxInvoices[0];
            invoiceMemo=R.isNil(taxInv)?"":taxInv.memo;
            memoTitle=<span>收票详情&nbsp;<p style={{color:"red"}}>验票退回原因：{invoiceMemo}</p></span>;
        }




        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {labelCol: { xs: {span: 8}, sm: {span: 8}}, wrapperCol: {xs: {span: 15}, sm: {span: 14}}};
        let footer = [];

        footer.push(<Button key="cancel" size="large"  onClick={this.handleCancel.bind(this)}>取消</Button>);

        if (this.state.type != OperatorConstant.view) {
            let text = "确认";
            if(this.state.type == OperatorConstant.add){
                text = "收票";
                footer.push(<Button key="save" size="large" loading={this.state.subloading} onClick={this.handleConfirm.bind(this, "1")}>保存发票</Button>); //参数1区分是否改变收票状态，1:不改变而只保存发票list
            }else if(this.state.type == OperatorConstant.approval){
                text = "确认收票";

            }else if(this.state.type == OperatorConstant.drawer_checkinvoice){
                text = "确认验票";
            }
            footer.push(<Button key="apply" size="large" loading={this.state.subloading} onClick={this.handleConfirm.bind(this, null)}>{text}</Button>);

        }



        let disable = (this.state.type == OperatorConstant.view ? true : false );

        return (
            <Modal maskClosable={false} visible={this.state.open} title={memoTitle} width={1000} wrapClassName="vertical-center-modal"
                   onCancel={this.handleCancel.bind(this)} footer ={footer}>

                <Inoviceheader wrappedComponentRef={(inst) => this.inoviceheader = inst} dispatch={this.props.dispatch}
                               dataSource={invoices}/>

                <Inoviceproducts wrappedComponentRef={(inst) => this.inoviceproducts = inst} dispatch={this.props.dispatch}
                                 dataSource={inoviceproductsList}/>


                {this.state.type == OperatorConstant.add || this.state.type == OperatorConstant.view?
                    <AddInvoice wrappedComponentRef={(inst) => this.addInvoice = inst} dispatch={this.props.dispatch}
                                dataSource={invoices}
                                type={this.state.type}
                                drawerList={this.props.drawerList}/>
                    :""}


                {this.state.type == OperatorConstant.approval ?
                    <Tabs>
                        <TabPane tab="审核" key="2">
                            <Form>
                                <Row>
                                    <Col span={12}>
                                        <FormItem {...formItemLayout} label="审核结果" hasFeedback>
                                            {getFieldDecorator('approvalresult', {
                                                rules: [{
                                                    required: true, message: '请选择审核结果！',
                                                }],
                                                initialValue: ''
                                            })(
                                                <Select style={{width: 230}} onChange={this.handleSelect.bind(this)}>
                                                    <Option value="4">审核通过</Option>
                                                    <Option value="6">审核不通过</Option>
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span={12}>
                                        <FormItem {...formItemLayout} label="备注" hasFeedback>
                                            {getFieldDecorator('approvalmemo', {
                                                rules: [{
                                                    required: this.state.require_memo, message: '请输入备注！',
                                                }],
                                            })(
                                                <TextArea/>
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Form>
                        </TabPane>
                    </Tabs>
                    :""}


                {this.state.type == OperatorConstant.drawer_checkinvoice ?
                    <Tabs>
                        <TabPane tab="发票认证" key="2">
                            <Form>
                                <Row>
                                    <Col span={12}>
                                        <FormItem {...formItemLayout} label="认证结果" hasFeedback>
                                            {getFieldDecorator('checkStatus', {
                                                rules: [{
                                                    required: true, message: '请选择认证结果！',
                                                }],
                                                initialValue: ''
                                            })(
                                                <Select style={{width: '100%'}} onChange={this.handleSelect.bind(this)}>
                                                    <Option value="5">认证通过</Option>
                                                    <Option value="7">认证不通过</Option>
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={12}>
                                        <FormItem {...formItemLayout} label="验票时间" hasFeedback>
                                            {getFieldDecorator('checkinvoicetime', {
                                                rules: [{
                                                    required: true, message: '请选择验票时间！',
                                                }],
                                                initialValue: ''
                                            })(
                                                <DatePicker style={{ width: "100%" }}
                                                    showTime={{format: 'YYYY-MM-DD'}}
                                                    format="YYYY-MM-DD"
                                                    placeholder="请选择时间"
                                               />
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span={12}>
                                        <FormItem{...formItemLayout} label="备注" hasFeedback>
                                            {getFieldDecorator('memo', {
                                                rules: [{
                                                    required: this.state.require_memo, message: '请输入备注！',
                                                }],
                                            })(
                                                <TextArea/>
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Form>
                        </TabPane>
                    </Tabs>
                    :""}




            </Modal>
        );
    }
})


